#!/usr/bin/env python
# -*- coding:utf-8 -*-

import makesentence as ms
import time

# refer to: https://www.jianshu.com/p/148b90c43301
def time_took(func):
    def calc_time(*args, **kwargs):
        start = time.time()
        func(*args, **kwargs)
        end = time.time()
        print("Time took: {0} sec".format(end-start))
    return calc_time

# gen ta file
def gen_data(filename, times):
    with open(filename, 'w') as f:
        for _ in range(1, times):
            line = " ".join(ms.sentence())
            f.write("{0}\n".format(line))

# read the full file and count the word
@time_took
def read_file(filename):
    with open(filename, 'r') as f:
        num = 0
        for word in f.read().split():
            if word == 'cat':
                num += 1
        print("the count of cat is {0} by read whole file".format(num))

# read line the file and count the word
@time_took
def read_line(filename):
    with open(filename, 'r') as f:
        num = 0
        for line in f.readlines():
            for word in line.split():
                if word == "cat":
                    num += 1
        print("the count of cat is {0} by read lines".format(num))
@time_took
def read_file_object(filename):
    num = 0
    infile = open(filename, encoding="utf_8")
    for line in infile:
        for word in line.split():
            if word == "cat":
                num += 1
    infile.close()
    print("the count of cat is {0} by read file object".format(num))

if __name__ == "__main__":
    file = './20221206_data.txt'
    gen_data(file, 50000000)
    read_file(file)
    read_line(file)
    read_file_object(file)